package com.project.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author : Yan
 * @Description : beetlsql config
 */
@Configuration
@Slf4j
public class BeetlSqlConfig {


    @Bean(initMethod = "init", name = "beetlConfig")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfigurable() {
        log.info("初始化数据库配置");
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader();
        beetlGroupUtilConfiguration.setResourceLoader(classpathResourceLoader);
        // 读取配置文件信息
        return beetlGroupUtilConfiguration;
    }

    @Bean(name = "datasource")
    public DataSource datasource(Environment env) {
        log.info("初始化连接数据库");
        HikariDataSource ds = null;
        try {
            String url = env.getProperty("spring.datasource.url");
            String userName = env.getProperty("spring.datasource.userName");
            String passWord = env.getProperty("spring.datasource.passWord");
            String driverClassName = env.getProperty("spring.datasource.driver-class-name");
            ds = new HikariDataSource();
            log.info(String.format("数据库地址：%s", url));
            ds.setJdbcUrl(url);
            log.info(String.format("数据库用户名：%s", userName));
            ds.setUsername(userName);
            log.info(String.format("数据库密码：%s", passWord));
            ds.setPassword(passWord);
            log.info(String.format("数据库类型：%s", driverClassName));
            ds.setDriverClassName(driverClassName);
            log.info("初始化连接数据库成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化连接数据库失败");
        }
        return ds;
    }

    //开启事务
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("datasource") DataSource datasource) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(datasource);
        return dsm;
    }


}
